 //2583.二叉树中的第 K 大层和
 //https://leetcode.cn/problems/kth-largest-sum-in-a-binary-tree/?envType=daily-question&envId=2024-02-23
class Solution {
public:
    long long kthLargestLevelSum(TreeNode* root, int k) {
        if(root == nullptr) return 0;
        queue<TreeNode*> q;
        vector<long long> ret;
        q.push(root);
        while(!q.empty())
        {
            int n = q.size();
            long long sum = 0;
            while(n--)
            {
                TreeNode* node = q.front(); q.pop();
                if(node->left) q.push(node->left);
                if(node->right) q.push(node->right);
                sum += node->val;
            }
            ret.push_back(sum);
        }
        sort(ret.begin(),ret.end());
        if(k > ret.size()) return -1;
        return ret[ret.size()-k];
    }
};